package com.hknc.btscale;

import android.app.Application;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;

import androidx.annotation.NonNull;

import com.danikula.videocache.HttpProxyCacheServer;
import com.hdl.CrashExceptioner;
import com.hknc.btscale.greendao.DaoMaster;
import com.hknc.btscale.greendao.DaoSession;

import cn.wandersnail.bluetooth.BTManager;
import cn.wandersnail.commons.poster.ThreadMode;

/**
 * 2021年12月8日09:34:01
 * 该项目为经典蓝牙版本
 */
public class BaseApplication extends Application implements Thread.UncaughtExceptionHandler{
    private static BaseApplication instance;
    public static BluetoothDevice sDevice;

    public static BaseApplication getInstance() {
        return instance;
    }

    private HttpProxyCacheServer proxy;
    public static  HttpProxyCacheServer getProxy(Context context){
        BaseApplication application= (BaseApplication) context.getApplicationContext();
        return application.proxy==null? (application.proxy=application.newProxy()):application.proxy;
    }
    private HttpProxyCacheServer newProxy() {
        return new HttpProxyCacheServer.Builder(this)
                .maxCacheSize(1024 * 1024 * 1024)       // 1 Gb for cache
                .build();
    }
    @Override
    public void onCreate() {
        super.onCreate();
        //设置Thread Exception Handler
        Thread.setDefaultUncaughtExceptionHandler(this);//异常崩溃重启APP
//        CrashExceptioner.init(this);//抓取崩溃信息并显示
        instance = this;
//        实例化有两种方式：
//        BTManager.getInstance().initialize(this);
        BTManager manager = BTManager.getBuilder()
                .setObserveAnnotationRequired(true)//不强制使用{@link Observe}注解才会收到被观察者的消息，强制使用的话，性能会好一些
                .setMethodDefaultThreadMode(ThreadMode.BACKGROUND)//指定回调方法和观察者方法的默认线程
                .build();
        manager.initialize(this);
        BTManager.isDebugMode = false;//开启日志打印
        initGreenDao();
    }

    /**
     * 初始化GreenDao,直接在Application中进行初始化操作
     */
    private void initGreenDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "aserbao.db");
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }

    private DaoSession daoSession;
    public DaoSession getDaoSession() {
        return daoSession;
    }

    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
        Intent intent = new Intent(this, ScanActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        System.out.println("uncaughtException");
        System.exit(0);
    }
}
